__author__ = 'shawhen'

import ctypes

from .. import Kernel32
from .. import WinDef

from ..shared import minwindef

from ....cstd import stdio


def ReadFile(hFile, nNumberOfBytesToRead, overlapped):
    """
    :param nNumberOfBytesToRead a python integer
    :param overlapped None==NULL
    :return (True/False, buf)
    """
    number_of_bytes_read = WinDef.DWORD(0)
    buf = ctypes.create_string_buffer(nNumberOfBytesToRead)
    nNumberOfBytesToRead = WinDef.DWORD(nNumberOfBytesToRead)
    if overlapped is None:
        overlapped = stdio.NULL
    else:
        overlapped = ctypes.byref(overlapped)
    result = Kernel32.Kernel32_dll.ReadFile(hFile, buf, nNumberOfBytesToRead, ctypes.byref(number_of_bytes_read), overlapped)
    if result == minwindef.FALSE:
        result = False
    elif result == minwindef.TRUE:
        result = True
    return result, buf.raw[:number_of_bytes_read.value]


def WriteFile(hFile, buf, overlapped):
    """
    :param buf a python bytes
    :param overlapped None==NULL
    :return (True/False, bytes_written)
    """
    number_of_bytes_written = WinDef.DWORD(0)
    if overlapped is None:
        overlapped = stdio.NULL
    else:
        overlapped = ctypes.byref(overlapped)
    result = Kernel32.Kernel32_dll.WriteFile(hFile, buf, len(buf), ctypes.byref(number_of_bytes_written), overlapped)
    if result == minwindef.FALSE:
        result = False
    elif result == minwindef.TRUE:
        result = True
    return result, number_of_bytes_written.value